package com.daguchuangyi.erp_android.productlist.paramsfilter;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.manager.ParameterManager;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.jude.utils.JUtils;

import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class ParamsFilterFragment extends Fragment {

    private OnFilterSelectListener mListener;

    public ParamsFilterFragment() {
        // Required empty public constructor
    }

    private TextView mCancelTv;
    private TextView mConfirmTv;

    private ChunkLinearLayout mFilterWrapper;
    private ScrollView mScrollView;
    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_params_filter, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mFilterWrapper = view.findViewById(R.id.filter_wrapper);
        mScrollView = view.findViewById(R.id.scroll_wrapper);
        mCancelTv = view.findViewById(R.id.cancel_tv);
        mConfirmTv = view.findViewById(R.id.confirm_tv);
        mCancelTv.setOnClickListener(v -> mListener.onCancelClicked());
        mConfirmTv.setOnClickListener(v -> {
            if (mFilterWrapper != null) {
                Map<Integer, ParameterManager.ParamCheckStatus> results = new HashMap<>();
                int childCount = mFilterWrapper.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    View subItem = mFilterWrapper.getChildAt(i);
                    if (subItem instanceof ParamFilterSectionView) {
                        Map<Integer, ParameterManager.ParamCheckStatus> checkResult = ((ParamFilterSectionView) subItem).getCheckResult();
                        if (checkResult.size() != 0) {
                            results.putAll(checkResult);
                        }
                    }
                }
                ParameterManager.getInstance().setParamsCheckStatus(results);
                ClassificationManager.getInstance().changeToParamsFilterMode();
            }
            mListener.onConfirmClicked();
        });
//        mFilterWrapper = new ChunkLinearLayout(getContext());
//        mFilterWrapper.setOrientation(LinearLayout.VERTICAL);
        int height = JUtils.dip2px(60);
        Subscription subscription = ParameterManager.getInstance().listParams(true)
                .flatMap(pair -> Observable.just(pair.second))
                .flatMap(paramsSectionWrapper -> Observable.just(paramsSectionWrapper.getParameters()))
                .concatMapIterable(parameters -> parameters)
                .filter(parameter -> parameter.getId() != ParameterManager.ID_CAD_IMAGE_OPTIONS
                        && parameter.getId() != ParameterManager.ID_PRODUCT_IMAGE_DEFAULT
                        && parameter.getId() != ParameterManager.ID_SAMPLE_OPTIONS
                        && parameter.getId() != ParameterManager.ID_STOCK_OPTIONS)
                .flatMap(parameter -> {
                    ParamFilterSectionView sectionView = new ParamFilterSectionView(getContext());
                    sectionView.bindParameter(parameter);
                    return Observable.just(sectionView);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(paramFilterSectionView -> {
                    LinearLayout.LayoutParams layoutParams =
                            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                    mFilterWrapper.addView(paramFilterSectionView, layoutParams);
                }, throwable -> {
                    JUtils.Log("load params error : " + throwable.getMessage());
                    throwable.printStackTrace();
                    ErrorHandler.handlerNetworError(throwable, "加载参数设置出错，请检查网络");
                    if (mListener != null) {
                        mListener.onCancelClicked();
                    }
                });
        mCompositeSubscription.add(subscription);

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFilterSelectListener) {
            mListener = (OnFilterSelectListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mCompositeSubscription.clear();
    }

    public interface OnFilterSelectListener {
        void onCancelClicked();

        void onConfirmClicked();
    }
}
